<?php
/**
 * 用户model
 * User: guojing
 * Date: 2020/4/5
 * Time: 22:21
 */
namespace app\api\model;

use app\common\library\Auth;
use think\Cookie;
use think\Log;
use think\Model;
use think\Session;

class User extends Model
{

    protected $name = 'user';

    public static function findInfoByCondition($condition = [], $isLock = 0)
    {
        if ($isLock == 1) {
            $user = self::where($condition)->lock(true)->find();
        } else {
            $user = self::where($condition)->find();
        }

        if ($user) {
            unset($user['password']);
            unset($user['salt']);
        }
        return $user;
    }

    public static function saveData($uid, $data = [])
    {
        if ($uid > 0) {
            return self::where(['id' => $uid])->update($data);
        }
    }

    /**
     * 获取当前登录用户uid
     * @param int $uid
     * @return int|mixed
     */
    public static function getCurrUid($uid = 0)
    {
        $authId = Auth::instance()->id;
        if ($authId) {
            return $authId;
        }

        $cookUid = Cookie::get('uid');
        $cookUid = (int)$cookUid;
        if ($cookUid) {
            $uid = $cookUid;
        } else {
            $sessUid = Session::get('login_uid');
            $sessUid = (int)$sessUid;
            if ($sessUid) {
                $uid = $sessUid;
            }
        }
        $uid = $uid ? (int)$uid : 0;
        return $uid;
    }

    public static function lockInfoByUid($uid)
    {
        $user = self::where(['id' => $uid])->field('id, money')->lock(true)->find();
        return $user;
    }

    public static function saveUidCache($uid)
    {
        if ($uid) {
            Cookie::set('uid', $uid);
            Session::set('login_uid', $uid);
        }
    }

}